package com.hdax.dm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.dm.constant.ErrConstant;
import com.hdax.dm.dto.LoginDto;
import com.hdax.dm.dto.UserDto;
import com.hdax.dm.entity.base.Image;
import com.hdax.dm.entity.user.DmUser;
import com.hdax.dm.exception.DmException;
import com.hdax.dm.feign.ImageFeign;
import com.hdax.dm.mappers.UserMapper;
import com.hdax.dm.mapstrucs.LoginDtoMapper;
import com.hdax.dm.mapstrucs.UserDtoMapper;
import com.hdax.dm.service.LoginService;
import com.hdax.dm.utils.Token.TokenUtil;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class LoginSImpl extends ServiceImpl<UserMapper,DmUser> implements LoginService {

    @Autowired
    private LoginDtoMapper LoginDtoMapper;

    @Autowired
    private UserDtoMapper userDtoMapper;

    @Autowired
    private ImageFeign imageFeign;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;



    @Override
    public CommonResponse<UserDto> queryPersonInfo(Integer uid) {
        QueryWrapper<DmUser> wrapper=new QueryWrapper<>();
        wrapper.eq("id",uid);
        DmUser user=getOne(wrapper);
        UserDto userDto= userDtoMapper.toTarget(user);
        userDto.setSex(user.getSex()+"");
        //------------------远程调用图片----------------
        Image image=imageFeign.image(uid.longValue(), 0L, 0L);
        String imageUrl=image==null?"": image.getImgUrl();

        userDto.setHeadUrl(imageUrl);
        return ResponseUtil.returnSuccess(userDto);
    }




    @Override
    public CommonResponse<LoginDto> login(String phone, String password) {
        QueryWrapper<DmUser> wrapper=new QueryWrapper<>();
        wrapper.eq("phone",phone);
        wrapper.eq("password",password);
        DmUser user=getOne(wrapper);
        LoginDto loginDto= LoginDtoMapper.toTarget(user);
        if (user==null){
            throw new DmException(ErrConstant.ErrCodeConstant.WRONG_CODE_PASSWORD,ErrConstant.ErrMsgConstant.WRONG_MSG_PASSWORD);
        }

        loginDto.setExtTime(TokenUtil.expireDate.toString());
        loginDto.setGenTime(TokenUtil.createDate.toString());
        String token= TokenUtil.createToken(user.getId().toString(),user.getNickName());
        loginDto.setToken(token);
        redisTemplate.opsForValue().set("token:"+user.getId(),token);

        return ResponseUtil.returnSuccess(loginDto);
    }
}
